/**
 * @file Client.c
 * @author your name (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2022-08-11
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>

#include"Client.h"

#define SERVER_IP   "192.168.2.178"
#define BUFFER_NUM  1024

int ClientInit(ClientTypedef *client)
{
    // 创建网络连接
    client->socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client->socket_fd == -1)
    {
        perror("Get fd fail\n");
        return -1;
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;     //协议
    server_addr.sin_port = htons(client->server_port);   //设定端口号，并进行大小端序的转换
    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr.s_addr);
    printf("%lx\n", server_addr.sin_addr.s_addr);
    int ret = connect(client->socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if(ret == -1)
    {
        perror("connect error");
        return -1;
    }

    return 0;
}

int ClientControl(ClientTypedef *client)
{
    if(client->status == sending)
    {
        int send_len;
        int read_len;  
        char file_buf[BUFFER_NUM] = {0};

        
        read_len = (unsigned int)fread(file_buf, 1, BUFFER_NUM, client->send_file_fp);  
        if(read_len < 0)
        {
            perror("read file");
            fclose(client->send_file_fp);
            return -1;
        }

        if(feof(client->send_file_fp))
        {
            client->status = waiting;
            fclose(client->send_file_fp);
        }

        send_len = send(client->socket_fd, file_buf, read_len, 0);
        if(send_len < 0)
        {
            perror("send data");
            fclose(client->send_file_fp);
            return -1;
        }

        // printf("send %d data", send_len);
    }

    return 0;
}

int SendFile(ClientTypedef *client)
{
    client->status = sending;
    client->send_file_fp = fopen(client->send_file_path, "rb");
    if(client->send_file_fp == NULL)
    {
        perror("open file");
        return -1;
    }

    return 0;
}